package com.ghxxzx.dagl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ghxxzx.dagl.entity.Daxx;
import com.ghxxzx.dagl.entity.Fg;
import com.ghxxzx.dagl.entity.User;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.FgMapper;
import com.ghxxzx.dagl.service.FgService;
import com.ghxxzx.dagl.utils.NullUtils;
import com.ghxxzx.dagl.utils.PageResultUtils;
import com.ghxxzx.dagl.vo.Buling;
import com.ghxxzx.dagl.vo.PageQuery;
import com.ghxxzx.dagl.vo.PageResult;
import com.ghxxzx.dagl.vo.ResultEntity;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class FgServiceImpl implements FgService {

    @Autowired
    private FgMapper fgMapper;
    @Value("${fg.fj}")
    private String path;

    @Override
    public ResultEntity addFg(MultipartFile multipartFile,User user,Fg fg) {
        String name = multipartFile.getOriginalFilename();
//        multipartFile.getContentType();
        int i = name.lastIndexOf(".");
//        String[] split = name.split("\\.");
        String substring = name.substring(i + 1);
        if (!substring.equals("pdf")){
            throw new JyException("请上传pdf文件");
        }
        QueryWrapper<Fg> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name.substring(0,i));
        Fg selectOne = fgMapper.selectOne(wrapper);
        if (selectOne!=null){
            fg.setId(selectOne.getId());
            fg.setName(name.substring(0,i));
            fgMapper.updateById(fg);
        }else {
            fg.setName(name.substring(0,i));
            fgMapper.insert(fg);
        }
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        FileOutputStream fileOutputStream1 = null;
        try {
            inputStream=multipartFile.getInputStream();
            fileOutputStream1 = new FileOutputStream(path + multipartFile.getOriginalFilename());
            IOUtils.copy(inputStream, fileOutputStream1);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream1 != null) {
                try {
                    fileOutputStream1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultEntity.ok();
    }

    @Override
    public ResultEntity queryAll() {
        QueryWrapper<Fg> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<Fg> fgs = fgMapper.selectList(wrapper);
        return ResultEntity.ok(fgs);
    }

    @Override
    public ResultEntity deleteById(Integer id) {
        Fg fg = fgMapper.selectById(id);
        fgMapper.deleteById(id);
        String filepath = path + fg.getName() + ".pdf";
        File file = new File(filepath);
        if (!file.exists()){
            throw new JyException("文件不存在");
        }
        file.delete();
        return ResultEntity.ok();
    }

    @Override
    public ResultEntity querykeyword(String keyword) {
        QueryWrapper<Fg> wrapper = new QueryWrapper<>();
        if (NullUtils.isNotNull(keyword)){
            wrapper.like("name",keyword);
        }
        List<Fg> fgs = fgMapper.selectList(wrapper);
        return ResultEntity.ok(fgs);
    }

    @Override
    public ResultEntity previewFg(String name, HttpServletRequest request, HttpServletResponse response) {
        String filepath = path + name + ".pdf";
        File file = new File(filepath);
        if (!file.exists()) {
            throw new JyException("文件不存在");
        }
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        ServletOutputStream out = null;
        File tempFile = null;
        try {
            inputStream = new FileInputStream(file);
            String suffix = filepath.substring(filepath.lastIndexOf(".") + 1);
            tempFile = File.createTempFile(Buling.Buyema(name), "." + suffix);
            outputStream = new FileOutputStream(tempFile);
            int byteCount = 0;
            byte[] bytes = new byte[1024 * 1024];
            while ((byteCount = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, byteCount);
            }
            inputStream = new FileInputStream(tempFile.getAbsolutePath());
            out = response.getOutputStream();
            IOUtils.copy(inputStream,out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return ResultEntity.ok();
        }
    }

    @Override
    public void downloadFg(String name, HttpServletRequest request, HttpServletResponse response) {
        String filepath = path + name + ".pdf";
        File file = new File(filepath);
        if (!file.exists()) {
            throw new JyException("文件不存在");
        }
        OutputStream out = null;
        BufferedInputStream is = null;
        byte[] b = new byte[4096];
        int len = 1024;
        // 清空response
        response.reset();
        response.setContentType("application/x-download");//设置response内容的类型 普通下载类型
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息
            out = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(file));
            while ((len = is.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String Buyema(String name){
        String z="";
        if (name.length()<3){
            for (int i = 0; i < 3 - name.length(); i++) {
                z+="0";
            }
            name=z+name;
        }
        return name;
    }
}
